import React, { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
// Assuming back-icon.png is in src/assets/images/ directory
// Make sure to create this path and add the image, or adjust the import path
import backIcon from '../assets/images/back-icon.png';

type BackgroundKey = 'morningGlow' | 'nightSky' | 'mistForest' | 'rippleLake' | 'pureCalm';

interface BackgroundStyle {
  name: string;
  gradient: string;
  haloColor: string;
  textColor?: string; // Optional: for completion message
}

const backgroundStyles: Record<BackgroundKey, BackgroundStyle> = {
  morningGlow: {
    name: '晨曦渐变',
    gradient: 'linear-gradient(to bottom, #FFDAB9, #87CEFA)',
    haloColor: 'rgba(255, 218, 185, 0.5)',
    textColor: '#E67E22', // Warm orange
  },
  nightSky: {
    name: '夜空柔光',
    gradient: 'linear-gradient(to bottom, #2c3e50, #8e44ad)',
    haloColor: 'rgba(142, 68, 173, 0.4)',
    textColor: '#D2B4DE', // Light purple
  },
  mistForest: {
    name: '晨雾森林',
    gradient: 'linear-gradient(to bottom, #6B8E23, #2E8B57)',
    haloColor: 'rgba(107, 142, 35, 0.6)',
    textColor: '#A9DFBF', // Soft green
  },
  rippleLake: {
    name: '静水涟漪',
    gradient: 'linear-gradient(to bottom, #20B2AA, #008080)',
    haloColor: 'rgba(0, 128, 128, 0.6)',
    textColor: '#A3E4D7', // Soft teal
  },
  pureCalm: {
    name: '极简纯色',
    gradient: 'linear-gradient(to bottom, #483D8B, #6A5ACD)',
    haloColor: 'rgba(106, 90, 205, 0.6)',
    textColor: '#CBC3E3', // Soft lavender
  },
};

const BREATH_DURATION = 6; // seconds for inhale/exhale - User changed this
const DEFAULT_MEDITATION_MINUTES = 5;
const DURATION_OPTIONS = [3, 5, 10, 15]; // Available meditation durations in minutes

const BreathPage: React.FC = () => {
  const navigate = useNavigate();
  const [selectedBackground, setSelectedBackground] = useState<BackgroundKey>('morningGlow');
  const [breathingPhase, setBreathingPhase] = useState<'inhale' | 'exhale'>('inhale');

  const [selectedDurationMinutes, setSelectedDurationMinutes] = useState(DEFAULT_MEDITATION_MINUTES);
  const [initialDurationSeconds, setInitialDurationSeconds] = useState(selectedDurationMinutes * 60);
  const [timeRemaining, setTimeRemaining] = useState(initialDurationSeconds);
  const [isSessionStarted, setIsSessionStarted] = useState(false); // New state for session start
  const [isTimerActive, setIsTimerActive] = useState(false); // Start inactive
  const [isTimerFinished, setIsTimerFinished] = useState(false);

  const currentBackground = backgroundStyles[selectedBackground];

  // Update initialDurationSeconds and timeRemaining when selectedDurationMinutes changes
  useEffect(() => {
    const newDurationSeconds = selectedDurationMinutes * 60;
    setInitialDurationSeconds(newDurationSeconds);
    setTimeRemaining(newDurationSeconds); // Reset time remaining when duration changes before start
  }, [selectedDurationMinutes]);

  // Breathing phase timer
  useEffect(() => {
    if (!isTimerActive || isTimerFinished || !isSessionStarted) return;

    const breathTimer = setInterval(() => {
      setBreathingPhase((prev) => (prev === 'inhale' ? 'exhale' : 'inhale'));
    }, BREATH_DURATION * 1000);
    return () => clearInterval(breathTimer);
  }, [isTimerActive, isTimerFinished, isSessionStarted]);

  // Meditation countdown timer
  useEffect(() => {
    if (!isTimerActive || isTimerFinished || timeRemaining <= 0 || !isSessionStarted) {
      if (timeRemaining <= 0 && !isTimerFinished && isSessionStarted) {
        setIsTimerActive(false);
        setIsTimerFinished(true);
      }
      return;
    }

    const countdownTimer = setInterval(() => {
      setTimeRemaining((prevTime) => prevTime - 1);
    }, 1000);

    return () => clearInterval(countdownTimer);
  }, [isTimerActive, timeRemaining, isTimerFinished, isSessionStarted]);

  // Auto-navigate after completion
  useEffect(() => {
    if (isTimerFinished && isSessionStarted) {
      const navigationTimer = setTimeout(() => {
        navigate('/main');
      }, 3000); // 3 seconds after completion message
      return () => clearTimeout(navigationTimer);
    }
  }, [isTimerFinished, isSessionStarted, navigate]);

  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  };

  const handleBackClick = useCallback(() => {
    if (isSessionStarted && !isTimerFinished) {
      // Optionally, add a confirmation dialog here before stopping an active session
      setIsSessionStarted(false);
      setIsTimerActive(false);
      // Reset timer to initial selected duration for next potential start
      setTimeRemaining(selectedDurationMinutes * 60);
      setIsTimerFinished(false); // Ensure it's not marked as finished if going back mid-session
    } else {
      navigate('/main');
    }
  }, [navigate, isSessionStarted, isTimerFinished, selectedDurationMinutes]);

  const handleStartSession = () => {
    setTimeRemaining(initialDurationSeconds); // Ensure timer starts with the selected duration
    setIsSessionStarted(true);
    setIsTimerActive(true);
    setIsTimerFinished(false);
  };

  // TODO: Implement a way for user to set initialDurationSeconds, e.g., from a modal or previous page. -- This is now handled by DURATION_OPTIONS

  return (
    <motion.div
      key={selectedBackground} // For background transition
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.8 }}
      style={{
        position: 'relative',
        width: '100vw',
        height: '100vh',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        background: currentBackground.gradient,
        // transition: 'background 0.8s ease-in-out', // Managed by AnimatePresence on a dedicated bg div
      }}
    >
      {/* Back Button - Always visible for now, but logic adjusted */}
      <motion.img
        src={backIcon}
        alt="Back"
        onClick={handleBackClick}
        whileHover={{ scale: 1.1, opacity: 0.8 }}
        transition={{ duration: 0.2 }}
        style={{
          position: 'absolute',
          top: '20px',
          left: '20px',
          width: '24px',
          height: '24px',
          cursor: 'pointer',
          zIndex: 30, // Ensure it's above other elements
        }}
      />

      {/* Dedicated Background Layer for Smooth Transitions */}
      <AnimatePresence mode="wait">
        <motion.div
            key={`bg-${selectedBackground}`} // Unique key for background div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.8 }}
            style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: currentBackground.gradient,
                zIndex: -1,
            }}
        />
      </AnimatePresence>

      {/* Preparation Phase UI: Duration selection and Start Button */}
      {!isSessionStarted && (
        <div style={{ zIndex: 20, textAlign: 'center', padding: '20px', background: 'rgba(0,0,0,0.2)', borderRadius: '15px', backdropFilter: 'blur(5px)' }}>
          <h2 style={{ color: 'white', marginBottom: '15px', fontSize: '20px' }}>选择冥想时长</h2>
          <div style={{ display: 'flex', justifyContent: 'center', gap: '10px', marginBottom: '25px' }}>
            {DURATION_OPTIONS.map(minutes => (
              <button
                key={minutes}
                onClick={() => setSelectedDurationMinutes(minutes)}
                style={{
                  padding: '10px 15px',
                  fontSize: '16px',
                  color: 'white',
                  background: selectedDurationMinutes === minutes ? 'rgba(255,255,255,0.4)' : 'rgba(255,255,255,0.2)',
                  border: '1px solid rgba(255,255,255,0.3)',
                  borderRadius: '8px',
                  cursor: 'pointer',
                  transition: 'background 0.3s'
                }}
              >
                {minutes} 分钟
              </button>
            ))}
          </div>
          <button
            onClick={handleStartSession}
            style={{
              padding: '12px 25px',
              fontSize: '18px',
              color: '#333',
              background: 'rgba(255, 255, 255, 0.9)',
              border: 'none',
              borderRadius: '8px',
              cursor: 'pointer',
              fontWeight: 'bold',
              transition: 'background 0.3s, transform 0.2s',
            }}
            onMouseOver={(e) => e.currentTarget.style.background = 'rgba(255, 255, 255, 1)'}
            onMouseOut={(e) => e.currentTarget.style.background = 'rgba(255, 255, 255, 0.9)'}
          >
            开始冥想
          </button>
        </div>
      )}

      {/* Timer Display (Only during active session) */}
      {isSessionStarted && !isTimerFinished && (
        <div style={{ position: 'absolute', top: '30px', textAlign: 'center', zIndex: 20 }}>
          <p style={{ fontSize: '14px', color: 'rgba(255,255,255,0.7)', marginBottom: '5px' }}>
            冥想中: {selectedDurationMinutes} 分钟
          </p>
          <p style={{ fontSize: '28px', color: 'white', fontWeight: 'bold', textShadow: '0 0 8px rgba(0,0,0,0.3)' }}>
            {formatTime(timeRemaining)}
          </p>
        </div>
      )}
      
      {/* Breathing Ball and Text (Only during active session) */}
      {isSessionStarted && !isTimerFinished && (
        <div style={{ zIndex: 10, textAlign: 'center', position: 'relative', top: '0%' }}>
          <motion.div
            initial={{ scale: 1, opacity: 0.8 }}
            animate={isTimerActive ? {
              scale: breathingPhase === 'inhale' ? 1.5 : 1,
              opacity: breathingPhase === 'inhale' ? 1 : 0.8,
            } : { scale: 1, opacity: 0.8 }} // Return to base when timer stops
            transition={{
              duration: BREATH_DURATION,
              ease: "easeInOut",
            }}
            style={{
              width: 150,
              height: 150,
              borderRadius: '50%',
              background: 'rgba(255, 255, 255, 0.3)',
              backdropFilter: 'blur(10px)',
              position: 'relative',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              boxShadow: '0 0 20px rgba(255,255,255,0.3)',
            }}
          >
            {/* Halo */}
            <motion.div
              initial={{ scale: 1.1, opacity: 0.7 }}
              animate={isTimerActive ? {
                scale: breathingPhase === 'inhale' ? 1.8 : 1.1,
                opacity: breathingPhase === 'inhale' ? 1 : 0.7,
              } : { scale: 1.1, opacity: 0.7 }} // Return to base when timer stops
              transition={{
                duration: BREATH_DURATION, // Halo duration should match ball
                ease: "easeInOut",
              }}
              style={{
                position: 'absolute',
                width: '100%',
                height: '100%',
                borderRadius: '50%',
                background: currentBackground.haloColor,
                filter: 'blur(25px)',
                zIndex: -1,
              }}
            />
          </motion.div>
          <motion.p
            key={breathingPhase + "_text"} // Keep key for text re-animation if needed
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: isTimerActive ? 1: 0, y: isTimerActive ? 0 : 10 }} // Fade out text if timer stops
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.5 }}
            style={{
              marginTop: '30px',
              fontSize: '24px',
              color: 'white',
              fontWeight: 'bold',
              textShadow: '0 0 10px rgba(0,0,0,0.3)',
            }}
          >
            {isTimerActive && (breathingPhase === 'inhale' ? '吸气' : '呼气')}
          </motion.p>
        </div>
      )}

      {/* Completion Message (Only when timer is finished and session was started) */}
      <AnimatePresence>
        {isTimerFinished && isSessionStarted && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.8, ease: "easeInOut" }}
            style={{
              position: 'absolute',
              textAlign: 'center',
              zIndex: 25, // Above ball, below back button if overlapping
              fontFamily: 'Noto Sans, PingFang SC, sans-serif',
              fontSize: '22px',
              lineHeight: '1.5',
              color: currentBackground.textColor || 'white', // Use specific color or default white
              padding: '20px',
              maxWidth: '80%',
              textShadow: '0 0 8px rgba(0,0,0,0.2)'
            }}
          >
            完成啦，希望你能把这份平静，带进接下来的时光。
          </motion.div>
        )}
      </AnimatePresence>

      {/* Background Selector (Only in preparation phase) */}
      {!isSessionStarted && (
         <div
            style={{
            position: 'absolute',
            bottom: '20px',
            right: '20px',
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            zIndex: 20,
            background: 'rgba(255,255,255,0.1)',
            padding: '10px',
            borderRadius: '10px',
            backdropFilter: 'blur(5px)',
            }}
         >
            {(Object.keys(backgroundStyles) as BackgroundKey[]).map((key) => (
            <button
                key={key}
                onClick={() => {
                    setSelectedBackground(key);
                    // Potentially reset timer or session if background changes mid-setup
                }}
                style={{
                padding: '8px 12px',
                border: '1px solid rgba(255,255,255,0.3)',
                borderRadius: '5px',
                background: selectedBackground === key ? 'rgba(255,255,255,0.3)' : 'rgba(255,255,255,0.1)',
                color: 'white',
                cursor: 'pointer',
                fontSize: '12px',
                minWidth: '100px',
                textAlign: 'center',
                transition: 'background 0.3s',
                }}
                title={backgroundStyles[key].name}
            >
                {backgroundStyles[key].name}
            </button>
            ))}
        </div>
      )}
    </motion.div>
  );
};

export default BreathPage;
